<?
$db = Database::singleton ();

try
{
	if (!isset ($_GET ['itemId']) || !$_GET['itemId'])
		throw new Exception (__ ('Error! Data losted.'));
	
	$itemId = $_GET['itemId'];
	
	$sth = $db->prepare ("SELECT _user._name as fiscal,_city._name as cityname, sgf.function.name as func, _login,siape, pis_pasep, rg,
							course, rga, bank, agence, count_number, bank, agence, situation, qthours, valuebyhour, street, number FROM _user 
						INNER JOIN sgf.user_team ON sgf.user_team._user = _user._id
						INNER JOIN sgf.team ON sgf.team.id = sgf.user_team.team
						INNER JOIN sgf.function ON sgf.function.id = user_team.function
						INNER JOIN _city ON _city._id = _user.city
						WHERE team.id = ". $itemId );

	$sth->execute ();
	
	$columns = array( '_ACADE_' => array ('nome', 'curso', 'rga', 'cpf', 'banco', 'agência', 'conta', 'valor líquido'),
					  '_SERVI_' => array ('matricula', 'nome', 'quantidade de horas trabalhadas', 'valor por hora', 'valor líquido'), 
					  '_EXTER_' => array ('nome','cpf','pis','rg', 'endereço', 'banco', 'agência', 'conta', 'função', 'valor líquido'));
					  
	$_out = array('_ACADE_' => array(), 
				  '_SERVI_' => array(), 
				  '_EXTER_' => array());

	$fileNames = array('_ACADE_' => 'academicos', 
					  '_SERVI_' => 'funcionarios', 
					  '_EXTER_' => 'externos');
				  
	while ($obj = $sth->fetch (PDO::FETCH_OBJ))
	{
		$obj->valuebyhour = str_replace (',', '',$obj->valuebyhour );
		$obj->valuebyhour = str_replace ('$', '',$obj->valuebyhour );
		
		$total = (int)$obj->qthours * (float) str_replace (',', '',$obj->valuebyhour );
		
		$total =  number_format($total, 2, ',', '.');
		
		if ($obj->situation == '_ACADE_')
			$_out [$obj->situation] [] = "'".$obj->fiscal."','".$obj->course."','".$obj->rga."','".$obj->_login."','".$obj->bank."','".$obj->agence."','".$obj->count_number."','".$total."'\r\n";
		else if ($obj->situation == '_SERVI_')
			$_out [$obj->situation] [] = "'".$obj->siape."','".$obj->fiscal."','".$obj->qthours."','".$obj->valuebyhour."','".$obj->bank."','".$total."'\r\n";
		else
			$_out [$obj->situation] [] = "'".$obj->fiscal."','".$obj->_login."','".$obj->pis_pasep."','".$obj->rg."','".$obj->street.",". $obj->number." - ".$obj->cityname."','".$obj->bank."','".$obj->agence."','".$obj->count_number."','".$obj->func."','".$total."'\r\n";
	}
	
	/*
	* Criando a pasta cache onde ficará o arquivo zipado
	*/
	
	require Instance::singleton ()->getCorePath () .'extra/pear.php';
	require Instance::singleton ()->getCorePath () .'extra/zip.php';
	
	$cache = Instance::singleton ()->getCachePath () . 'zip/';
	
	$zip = new Archive_Zip ($cache . 'folha_pagamento.zip');
	
	

	if (!file_exists ($cache) && !@mkdir ($cache, 0777))
		throw new Exception (__ ('Unable create directory [ [1] ]!', $cache));
	
	$count = 0;

	while (TRUE)
	{
		$hash = '';

		mt_srand (makeSeed ());

		while (strlen ($hash) < 5)
			$hash .= substr ('0123456789', mt_rand (0,9), 1);

		$aux = $cache . time () .'_'. User::singleton ()->getId () .'_'. $hash;

		if (file_exists ($aux))
			continue;

		if (@mkdir ($aux, 0777))
			break;

		if ($count++ >= 10)
			throw new Exception (__ ('Unable create directory [ [1] ]!', $aux));
	}

	$aux = $cache = $aux ."/" ;
	
	
	foreach ($columns as $index => $column)
	{
		$handle = fopen ($cache . $fileNames[$index] . '.csv', 'w+');
		
		fwrite ( $handle, implode("','", $column) . "\r\n" );
		
		foreach ($_out [$index] as $values)
			fwrite ( $handle, $values );
		
		fclose ($handle);
	}

	$files = compress ($cache, TRUE);
	
	if (!$zip->create ($files, array ('remove_path' => $cache)))
		throw new Exception ('Erro ao tentar criar arquivo Zip: '. $zip->_error_string);
	
	$cache = Instance::singleton ()->getCachePath () . 'zip/';
	
	$binary = fopen ($cache .'folha_pagamento.zip', 'rb');

	$buffer = fread ($binary, filesize ($cache .'folha_pagamento.zip'));
	
	fclose ($binary);
	
	header('Content-Type: application/force-download');
	header('Content-Disposition: attachment; filename=folha_pagamento.zip');
	
	echo $buffer;

	foreach ($files as $file )
		@unlink (  str_replace('\\','' , $file));
	@rmdir ($aux );
}
catch (PDOException $e)
{
	toLog ($e->getMessage ());
}
catch (Exception $e)
{
	toLog ($e->getMessage ());
}
?>